

// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html


var curMod = cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    statics: {
        _instance: null,
        InterstitialAdId: '167003',
        RewardedVideoAdId: ['166997', '166998', '166999', '167000', '167001', '167424'],
        BannerIds: ['166982', '166985', '166986', '166987', '166988', '166991', '166993', '166994', '166995'], //, 'adunit-905904089942c58e'],

        ShareTitle: '高分全凭手速快！',
        //ShareImgId: '5JWEBFBdTHiZ5EcslmutbA==', // 通过 MP 系统审核的图片编号
        //ShareImgUrl: 'https://mmocgame.qpic.cn/wechatgame/3gfJUsiaHCx28sibf4QvxkWEwK6UicbQricJn4M7ia9OoUIPaDXXn1tib6eSZWtpu7hOGz/0',

        _wxUserInfo: {},
        _systemInfo: {},

        Instance() {
            return curMod._instance;
        },

        GetInfo() {
            return curMod._wxUserInfo;
        },
    },

    onLoad() {
        console.log('vivo onload, curMod._instance=', curMod._instance);
        if (curMod._instance) {
            return;
        }
        curMod._instance = this;
        //...
        return;
        this.getOppoInfo();//用户登录，获取用户信息
    },

    start() {
    },

    // update (dt) {},
    //分享
    shareAppMessage() {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        var self = this;

        require('GameMgr').Instance().showTip("暂无分享功能", 0, "取消", "确定", function () {
        }, function () { return; });
    },




    onCreatDeskIco() {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        if (require('GameMgr').Instance().getLogin().deskBan === 1) {
            require('GameMgr').Instance().hidDeskBan();
            return;
        }
        qg.hasShortcutInstalled({
            success: function (res) {
                // 判断图标未存在时，创建图标
                if (res == false) {
                    qg.installShortcut({
                        success: function () {
                            // 执行用户创建图标奖励
                            require('GameMgr').Instance().sendData("setDeskBan", { "deskBan": 1, }, function (data) {
                                if (data.code === 0) {
                                    console.log("添加桌面奖励", data);
                                    var localCoin = require('GameMgr').Instance()._localCoin += 10000;
                                    require('GameMgr').Instance().setMoney(localCoin);
                                    require('GameMgr').Instance().showTip("恭喜你获得奖励\n<img src='enjoy2'/>x10000", 0, "取消", "确定", function () {
                                    }, function () { });
                                    require('GameMgr').Instance().hidDeskBan();
                                }
                                else {
                                    console.log("连接失败", data);
                                    return;
                                };
                            });
                        },
                        fail: function (err) { },
                        complete: function () { }
                    })
                }
            },
            fail: function (err) { },
            complete: function () { }
        })
    },

    //显示插屏广告
    showInterstitialAd() {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        var interstitialAd = qg.createInsertAd({
            adUnitId: curMod.InterstitialAdId
        })
        interstitialAd.load();

        interstitialAd.onLoad(function () {
            interstitialAd.show();
            console.log('插屏视频广告加载')
        });

        interstitialAd.onError(function (err) {
            console.log(err.errCode, err.errMsg)
            console.log("插屏视频广告加载失败", err)
        });
        /*
                interstitialVideoAd.onClose(function () {
                    console.log('插屏视频广告关闭')
                });
                interstitialVideoAd.onShow(function () {
                    console.log('插屏视频广告展示')
                });
        */
    },
    //显示视频广告
    showRewardedVideoAd(index) {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }// showToast 上线之前一定要去掉!
        // 错误的回调，creat的是在onerror里面，load，show等的回调在自己的catch里面

        console.log("激励广告加载", index);
        let rewardedAd;
        rewardedAd = qg.createRewardedVideoAd({
            adUnitId: curMod.RewardedVideoAdId[index]
        });

        rewardedAd.load();

        rewardedAd.onLoad(function () {
            console.log('激励视频加载成功')
            rewardedAd.show();
        })

        rewardedAd.onClose(function (res) {
            if (res.isEnded) {
                console.log('激励视频广告完成，发放奖励')
                require('GameMgr').Instance().ShowADrewords();
                require('GameMgr').Instance().setDaily(2);
            } else {
                console.log('激励视频广告取消关闭，不发放奖励')
                require('GameMgr').Instance().showTip("中途退出，获取奖励失败", 0, "取消", "确定", function () {
                }, function () { return; });
            }
        })
        var self = this;
        rewardedAd.onError(function (err) {
            console.log(err);
            rewardedAd.show();
            require('GameMgr').Instance().showTip(err, "获取视频失败\n请稍后再试", 0, "取消", "确定", function () {
            }, function () { return; });
        })
    },

    //显示底部广告
    showBannerAd(index) {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        console.log("创建banner广告", index);


        var windowSize = cc.winSize;

        let bannerHeight = 300;
        let bannerWidth = windowSize.width;

        this._bannerAds = qg.createBannerAd({
            adUnitId: curMod.BannerIds[index],
            style: {
            }
        })
        this._bannerAds.show();
        this._bannerAds.onError(function (err) {
            console.log("banner广告展示失败");
            console.log(err);
        })
    },

    //banner重加载
    retryShow() {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        let bannerAdRetey = qg.createBannerAd({
            posId: 'xxxxx',
            style: {}
        })
        let adShowRetry = bannerAdRetey.show()
        adShowRetry && adShowRetry.catch((error) => {
            console.log("banner广告展示失败-重试")
            console.log(JSON.stringify(error))
        })
    },
    //隐藏所有底部广告
    hideBannerAds() {
        if (require('GameMgr').Instance().ApiType !== 4) {
            return;
        }
        if (this._bannerAds) {
            this._bannerAds.hide();
        }
        this._bannerAds.onHide(function () {
            console.log('banner 广告隐藏')
        })
    },
    /**
     * 获取微信信息
     */
    getOppoInfo() {
        var id = require('GameMgr').Instance().ApiType;
        console.log("渠道ID：" + id);
        var self = this;
        //if (require('GameMgr').Instance().ApiType === 3) {
        if (qg.getSystemInfoSync().platformVersionCode >= 1053) {
            qg.login({
                success: function (res) {
                    var data = JSON.stringify(res.data);
                    console.log(data);
                    console.log("登录成功", res);
                    console.log(res);
                    if (res.data.token) {
                        require('GameMgr').Instance().setresCode(res.data.token);
                        console.log('当前用户信息: ' + JSON.stringify(res.data));
                        curMod._wxUserInfo = res.data.token;
                        // 使用token进行服务端对接
                        require('GameMgr').Instance().sendData("login", { "code": res.data.token, "channelId": 4 }, function (data) {
                            if (data.code === 0) {
                                console.log("返回数据", data);
                                require('GameMgr').Instance().setLogin(data.uid, data.token, data);
                                require('GameMgr').Instance().setGameStart();
                                var imgurl = curMod._wxUserInfo.avatar + "?aaa=aa.jpg";
                                require('GameMgr').Instance().setplUrl(imgurl);
                                var name = res.data.nickName;
                            }
                            else {
                                console.log("连接失败", data);
                                require('GameMgr').Instance().showTip("连接出错", 2, "取消", "确定", function () {
                                    cc.director.loadScene('LoadScene');
                                }, function () {
                                    cc.director.loadScene('LoadScene');
                                    return;
                                });
                                return;
                            }
                        });
                    }
                },
                fail: function (res) {
                    // errCode、errMsg
                    console.log(JSON.stringify(res));
                    console.log('登录失败' + JSON.stringify(err));
                    //cc.director.loadScene('LoadScene');
                    self.setLogin() // 重新登录
                }
            });
        }
    },

    printInfo(res) {
        // console.log('设备品牌:', res.brand)
        // console.log('设备型号:', res.model)
        // console.log('设备像素比:', res.pixelRatio)
        // console.log('屏幕宽度:', res.windowWidth)
        // console.log('屏幕高度:', res.windowHeight)
        // console.log('状态栏的高度:', res.statusBarHeight)
        // console.log('微信设置的语言:', res.language)
        // console.log('微信版本号:', res.version)
        // console.log('操作系统及版本:', res.system)
        // console.log('客户端平台:', res.platform)
        // console.log('用户字体大小:', res.fontSizeSetting)
        // console.log('客户端基础库版本 :', res.SDKVersion)
        // console.log('设备性能等级:', res.benchmarkLevel)
        if (res.system.indexOf('Android') != -1) {
            curMod._isAndroid = true;
        }
    },
});
